var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/admin/userRouter');
const JWT = require('./utils/JWT');
const newsRouter = require('./routes/admin/newsRouter');
const productRouter = require('./routes/admin/productRouter');
const webNewRouter = require('./routes/web/newsRouter')
const webProductRouter = require('./routes/web/productRouter')

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


// 前台新闻模块
app.use('/web',webNewRouter)
app.use('/web',webProductRouter )

// 验证token

app.use((req, res, next) => {
  // 如果token有效则放行
  // 判断是否是登录请求
 if (req.url === '/admin/user/login' && req.method === 'POST') {
  next() 
  return 
 }
//  获取前端传递的token数据

const token  = req.headers.authorization.split(' ')[1] // 将token从请求头中提取出来
if (token) {
  // 校验token的有效性
  const playload = JWT.verify(token)
    if (playload) {
      // 重新生成token\
      const newToken = JWT.generate({
        _id: playload._id,
        username: playload.username
      }, "1d")
      res.header("Authorization", newToken)
      console.log(playload);
      next()

    }else {
      res.status(401).send({
        erroeCode:  401,
        message: 'token无效'
      })

    }
}
})

app.use('/', indexRouter);
// 用户模块
app.use('/admin',usersRouter)
// 新闻模块
app.use('/admin',newsRouter)

app.use('/admin', productRouter)


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});





// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
